/**
 * 人才库-简历列表(宽/窄)
 */
import React, { useEffect, useState } from 'react';
import { Table, Cascader, Icon as AntdIcon, Row, Tooltip } from 'antd';
import { TableFilter } from '@/components';
import { getDict, getDisplayText } from '@/utils/dataDictUtil';
import { LAST_POST_STATUS, SEX, STAGE_TYPE, RECOMMEND_TYPE_VALUES } from '@/pages/Recruitment/dictionary';
import { Operates } from '@/pages/Recruitment/components';
import AuthComponent from '@/utils/auth/AuthComponent';
import { history } from 'umi'
import authHelper from '@/utils/auth/helper';
import { RecommendOperate, TalentMajorInfoCard } from '../../containers/index';
import { TalentsBlackListOperate, TalentsJoinSeniorOperate } from '../../containers/operate';
import styles from '../index.less';

import {
    renderLastPost,
    renderNameWithReadFlag,
    renderNameWithReadFlagTitle,
    renderShortDate,
    renderTalentDegree
} from '../../renderUtil';
import useChannelDict from '../../useChannelDict';

const { checkCode } = authHelper;

const getResumeStep = value => {
    if (value.length === 1) {
        return [value];
    }
    return [value.slice(0, 1), value.slice(1)];
};

const EmptyFilter = ({ confirm, setSelectedKeys, value }) => {
    useEffect(() => {
        setSelectedKeys(value && value !== 'all' ? [value] : []);
        confirm();
    }, [value]);
    return <span />;
};
const ResumeCardTable = ({
    loading,
    dataSource,
    condition,
    onJumpDetail,
    onRefresh,
    currTab,
    pageType,
    isSetting,
    ...rest
}) => {
    const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};
    const [agreeTypeList, setAgreeTypeList] = React.useState([]); // 学历
    const { channelDict = [] } = useChannelDict(); // 人才渠道
    // 字典获取
    React.useEffect(() => {
        getDict('agreeType').then(ret => setAgreeTypeList(ret));
    }, []);
    const [phaseValue, setPhaseValue] = useState('');
    const getPhaseValue = phaseValue || condition.phase;
    const onJumpSetting = () => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/setting',
            query: {
                activeKey: '7'
            },
            state: { tabRoute: true, tabRefresh: true }
        });
    };
    const onJumpDemandDetail = record => {
        const { recruitId, resumeStep } = record;
        // resumeStep: 1:简历 2：候选 3：面试 4：录用
        const activeKeys = {
            1: '2',
            2: '3',
            3: '4',
            4: '5'
        };
        history.push({
            pathname: '/office/personnelManagement/recruitment/demand/detail',
            query: {
                id: recruitId,
                activeKey: activeKeys[resumeStep] || '2'
            }
        });
    };

    const columns = [
        currTab === '1'
            ? {
                  title: <span style={{ marginLeft: '16px' }}>姓名</span>,
                  dataIndex: 'talentName',
                  render: (_, record) => (
                      <div style={{ cursor: 'pointer' }}>
                          <TalentMajorInfoCard talent={record} />
                      </div>
                  )
              }
            : {
                  title: renderNameWithReadFlagTitle('姓名'),
                  dataIndex: 'readFlag',
                  render: (value, record) => {
                      const { talentName = '--', showReadFlag } = record;
                      return renderNameWithReadFlag(talentName, value, showReadFlag);
                  }
              },
        ...(currTab === '2'
            ? [
                  {
                      title: '性别',
                      dataIndex: 'talentSex',
                      width: 80,
                      filteredValue: condition.talentSex ? [condition.talentSex] : [],
                      filters: SEX,
                      filterMultiple: false,
                      filterDropdown: filterProps => <TableFilter {...filterProps} />,
                      render: sex => getDisplayText(SEX, sex)
                  },
                  {
                      title: '学历',
                      dataIndex: 'talentDegree',
                      width: 100,
                      filteredValue: condition.talentDegree ? [condition.talentDegree] : [],
                      filters: agreeTypeList,
                      filterMultiple: false,
                      filterDropdown: filterProps => <TableFilter {...filterProps} />,
                      render: (val, record) =>
                          renderTalentDegree(getDisplayText(agreeTypeList, val), record.talentEduDetailVOList)
                  },
                  {
                      title: '最近工作',
                      dataIndex: 'lastPost',
                      render: (val, record) => renderLastPost(val, record.talentWorkDetailVOList)
                  },
                  {
                      title: '在职情况',
                      dataIndex: 'lastPostStatus',
                      filteredValue: condition.lastPostStatus ? [condition.lastPostStatus] : [],
                      filters: LAST_POST_STATUS,
                      filterMultiple: false,
                      filterDropdown: filterProps => <TableFilter {...filterProps} />,
                      render: val => getDisplayText(LAST_POST_STATUS, val)
                  }
              ]
            : []),
        {
            title: '应聘岗位',
            dataIndex: 'dutyName',
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => {
                if (text && record.dutyCode) {
                    return checkCode('office:recruitment:course') ? (
                        <span
                            type="link"
                            className={styles.link}
                            onClick={() => {
                                onJumpDemandDetail(record);
                            }}
                        >
                            {text}
                        </span>
                    ) : (
                        text
                    );
                }
                return (
                    <Row align="middle">
                        <span style={{ marginRight: '4px', color: 'red' }}>{text || '未匹配'}</span>
                        {/* <Tooltip title={record.dutyCode ? '未匹配到招聘岗位' : '未匹配'}> */}
                        <Tooltip title="未匹配到招聘岗位">
                            <AntdIcon type="question-circle" />
                        </Tooltip>
                    </Row>
                );
            }
        },
        {
            title: '阶段',
            dataIndex: 'resumeGlobalStatus',
            filteredValue: getPhaseValue && getPhaseValue !== 'all' ? getPhaseValue : '',
            filterDropdown: filterProps => <EmptyFilter {...filterProps} value={getPhaseValue} />,
            filterIcon: (
                <Cascader
                    fieldNames={{ label: 'text' }}
                    options={[
                        {
                            value: 'all',
                            text: '全部'
                        },
                        ...STAGE_TYPE
                    ]}
                    value={getPhaseValue && getPhaseValue !== 'all' ? getResumeStep(getPhaseValue) : ['all']}
                    onChange={value => {
                        setPhaseValue(value.join(''));
                    }}
                >
                    <AntdIcon type="filter" theme="filled" />
                </Cascader>
            ),
            filterMultiple: false,
            render: (_, record) => record.resumeStepName
        },
        {
            title: '状态',
            dataIndex: 'resumeStatusName',
            width: 100
        },
        // {
        //     title: '渠道',
        //     dataIndex: 'notesSource',
        //     filteredValue: condition.notesSource ? [condition.notesSource] : [],
        //     filters: channelDict,
        //     filterMultiple: true,
        //     filterDropdown: filterProps => <TableFilter {...filterProps} />,
        //     // render: (_, record) => getDisplayText(channelDict, val)
        //     render: (_, record) => record.notesSourceDetail
        // },
        {
            title: '渠道',
            dataIndex: 'notesSourceList',
            filteredValue: condition.notesSourceList || [],
            filters: channelDict,
            filterMultiple: true,
            render: (val, record) => getDisplayText(channelDict, record.notesSource)
        },
        // {
        //     title: '入库时间',
        //     dataIndex: 'updateTime',
        //     sorter: (a, b) => {
        //         const aTime = new Date(a.updateTime).getTime();
        //         const bTime = new Date(b.updateTime).getTime();
        //         return aTime - bTime;
        //     },
        //     render: val => renderShortDate(val)
        // },
        {
            title: '入库时间',
            dataIndex: 'updateTime',
            sortOrder: condition.orderByFieldActive,
            sorter: () => {},
            render: val => renderShortDate(val)
        },
        {
            title: '操作',
            dataIndex: 'action',
            width: 180,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (_, record) => {
                const { talentCode, resumeStep, dutyCode, resumeLabel, recruitList = [], advanceFlag } = record;
                const isLauncher = recruitList.some(item => item?.launchEmployeeCode === user.employeeCode);
                const isPrincipal = recruitList.some(item => item?.principalEmployeeCode === user.employeeCode);

                // record.resumeLabel 简历状态枚举：0=无标签 1=应聘中 2=已取消(各种取消) 3=淘汰(各种淘汰) 4 已入职
                // 未匹配到招聘岗位的新简历阶段 或 在招聘环节中“淘汰”或“已取消”状态 推荐到岗位
                const recommendStatus = (resumeStep === 0 && !dutyCode) || [2, 3].includes(resumeLabel);
                let messageType = 0; // 黑名单提示语类型
                // 淘汰或已取消的状态，不出现tip提示
                if (![2, 3].includes(resumeLabel)) {
                    // 提示类型1：应聘中：【面试】至【录用】阶段
                    if ([3, 4].includes(resumeStep) && resumeLabel === 1) messageType = 1;
                    // 提示类型2：【简历】【候选】阶段
                    if ([1, 2].includes(resumeStep)) messageType = 2;
                }

                let tooltipTitle = null; // 加入高级库的Title展示
                // 不符合加入高级库条件
                if (!advanceFlag && pageType === 'common') {
                    // 是否设置了高级库
                    if (isSetting) {
                        // 设置过高级库
                        tooltipTitle = (
                            <Row align="middle" justify="center">
                                <span>不符合条件</span>
                                <AuthComponent code="office:recruitment:setting:talent">
                                    <a style={{ marginLeft: 4 }} onClick={onJumpSetting}>
                                        查看
                                    </a>
                                </AuthComponent>
                            </Row>
                        );
                    } else {
                        // 未设置高级库
                        tooltipTitle = (
                            <Row align="middle" justify="center">
                                <span>未设置条件</span>
                                <AuthComponent code="office:recruitment:setting:talent">
                                    <a style={{ marginLeft: 4 }} onClick={onJumpSetting}>
                                        设置
                                    </a>
                                </AuthComponent>
                            </Row>
                        );
                    }
                }

                const defaultNoticeEmployee = new Set();
                record.recruitList.forEach(item => {
                    defaultNoticeEmployee.add(item.launchEmployeeCode);
                    defaultNoticeEmployee.add(item.principalEmployeeCode);
                });

                const operates = [
                    <RecommendOperate
                        resumeId={record.id}
                        onConfirm={onRefresh}
                        type={recommendStatus ? RECOMMEND_TYPE_VALUES.COMMON : RECOMMEND_TYPE_VALUES.OTHER}
                        weedOutDisabled={!(isPrincipal || isLauncher)}
                        talentCode={talentCode}
                        showSelect={false}
                    />,
                    <TalentsBlackListOperate
                        talentCode={talentCode}
                        operateType="add"
                        onRefresh={onRefresh}
                        messageType={messageType}
                        resumeStep={resumeStep}
                    />,
                    <TalentsJoinSeniorOperate
                        talentCode={talentCode}
                        operateType={pageType === 'common' ? 'add' : 'remove'}
                        onRefresh={onRefresh}
                        tooltipTitle={tooltipTitle}
                        disabled={!advanceFlag && pageType === 'common'}
                        defaultNoticeEmployee={Array.from(defaultNoticeEmployee)}
                    />
                ];
                return <Operates operates={operates} />;
            }
        }
    ];
    return (
        <Table
            {...rest}
            rowKey="id"
            bordered={false}
            columns={columns}
            loading={loading}
            dataSource={dataSource}
            pagination={false}
            onRow={record => ({
                onClick: () => {
                    const { readFlag, talentCode } = record;
                    if (onJumpDetail) onJumpDetail(readFlag, talentCode);
                }
            })}
        />
    );
};
export default ResumeCardTable;
